/**
 * Patient Controller
 */
patientApp.controller('PatientCtrl',
    ['$scope', '$filter', '$http', 'ngTableParams', 'datepickerPopupConfig',
    function($scope, $filter, $http, ngTableParams, datepickerPopupConfig)
    {
		$scope.patient = null;
		
		$scope.editingPatient = {
	        fName: "",
	        middleInitial: "",
	        lName: "",
	        phone: "",
	        address1: "",
	        address2: "",
	        city: "",
	        state: "",
	        gender: "",
	        passw1: "",
	        passw2: "",
	        dateAdded: null
		}
		
        $scope.patients = new Array();
		
		$scope.selectedPatients = function() {
			var selectedPatients = new Array();
			for(var patient in $scope.patients) {
				if(typeof($scope.patients[patient].selected) !== 'undefined' && $scope.patients[patient].selected == true) {
					selectedPatients.push($scope.patients[patient]);
				}
			}
			return selectedPatients;
		}
		
		$scope.selectAll = {selected: false};
        $scope.mode = "New";
        $scope.incomplete = false;
        $scope.errorMessages = new Array();
        $scope.tableParameters = null;
        
        $scope.datePicker = {
            opened: false,
            closeText: 'Close'
        }
        
        $scope.genderOptions = [
    	    {
    	    	label: "Male",
    	    	value: "M"
    	    },
    	    {
    	    	label: "Female",
    	    	value: "F"
    	    }
        ];
        
        $scope.init = function() {
            Utility.activateSidebarNav("sidebarNavigation", "#/patients/");
            
            $("#btnSelectAll").on('click', function(e) {
            	$scope.$apply(function() {
	            	if($scope.selectAll.selected) {
	            		$scope.selectAll.selected = false;
	            	}
	            	else {
	            		$scope.selectAll.selected = true;
	            	}
	            	
	            	for(var patient in $scope.patients) {
            			$scope.patients[patient].selected = $scope.selectAll.selected;
            		}
            	});
            });
            
            $("#dlgEditPatient").on('shown.bs.modal', function(e) {
                $("#txtFirstName").focus();
            });
            
            $("#dlgEditPatient").on('hidden.bs.modal', function(e) {
            	Utility.resetAngularFormErrors($scope, "editPatientForm");
            });
            
            $scope.$watch("editingPatient.passw2", function(newValue, oldValue, scope) {
            	scope.validatePassword();
            });
            
            $scope.tableParameters = new ngTableParams(
                {
                    page: 1,
                    count: 10,
                    sorting: {
                    	lName: 'asc'
                    }
                },
                {
                    total: $scope.patients.length,
                    getData: function($defer, params) {
                    	var orderedData = params.sorting() ? $filter('orderBy')($scope.patients, params.orderBy()) : $scope.patients;
                        params.total($scope.patients.length);
                        $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
                    }
                }
            );
            
            datepickerPopupConfig['datepickerPopup'] = 'dd-MMM-yyyy';
            
            $scope.refreshPatients();
        }
        
        $scope.updateSelectAll = function() {
        	var allSelected = true;
        	
        	for(var patient in $scope.patients) {
        		if(!$scope.patients[patient].selected) {
        			allSelected = false;
        			break;
        		}
        	}
        	
        	if(allSelected) {
        		$scope.selectAll.selected = true;
        		$("#btnSelectAll").addClass("active");
        	}
        	else {
        		$scope.selectAll.selected = false;
        		$("#btnSelectAll").removeClass("active");
        	}
        }
        
        $scope.refreshPatients = function() {
            $http({
                method: "GET",
                url: "/PatientFirst/services/patientservice/patients"
            }).success(
                function(responseModel, status, headers, config) {
                    if(responseModel.status == Utility.jsonResponse.SUCCESS) {
                        $scope.patients = responseModel.data;
                        if($scope.tableParameters != null) {
                            $scope.tableParameters.reload();
                        }
                    }
                    else {
                        Utility.showAlert("alertContainer", "danger", true, 3, "<strong>Error!</strong> An exception occurred while trying to load data: " + responseModel.message);
                    }
                }
            ).error(
                function(data, status, headers, config) {
                    Utility.showAlert("alertContainer", "danger", true, 3, "<strong>Error!</strong> An attempt to load data has failed.");
                }
            );
        }
        
        $scope.createPatient = function() {
        	$scope.patientId = -1;
        	
        	$scope.patient = null;
            $scope.mode = "New";
            $scope.editingPatient.fName = "";
            $scope.editingPatient.middleInitial = "";
            $scope.editingPatient.lName = "";
            $scope.editingPatient.phone = "";
            $scope.editingPatient.address1 = "";
            $scope.editingPatient.address2 = "";
            $scope.editingPatient.city = "";
            $scope.editingPatient.state = "";
            $scope.editingPatient.gender = "";
            $scope.editingPatient.passw1 = "";
            $scope.editingPatient.passw2 = "";
            $scope.editingPatient.dateAdded = null;
        }
        
        $scope.editPatient = function(id) {
        	$scope.patientId = id;
            
            $scope.mode = "Edit";
            for(var patient in $scope.patients) {
                if($scope.patients[patient].id == id) {
                	$scope.patient = $scope.patients[patient];
                	
                	$scope.editingPatient.patient = $scope.patients[patient];
                    $scope.editingPatient.fName = $scope.patients[patient].fName;
                    $scope.editingPatient.middleInitial = $scope.patients[patient].middleInitial;
                    $scope.editingPatient.lName = $scope.patients[patient].lName;
                    $scope.editingPatient.phone = $scope.patients[patient].phone;
                    $scope.editingPatient.address1 = $scope.patients[patient].address1;
                    $scope.editingPatient.address2 = $scope.patients[patient].address2;
                    $scope.editingPatient.city = $scope.patients[patient].city;
                    $scope.editingPatient.state = $scope.patients[patient].state;
                    $scope.editingPatient.gender = $scope.patients[patient].gender;
                    $scope.editingPatient.passw1 = $scope.patients[patient].password;
                    $scope.editingPatient.passw2 = $scope.patients[patient].password;
                    $scope.editingPatient.dateAdded = $scope.patients[patient].dateAdded;
                    break;
                }
            }
        }
        
        $scope.setPatient = function(patient) {
        	$scope.patient = patient;
        }
        
        $scope.savePatient = function() {
        	if($scope.patient != null) {
        		$scope.patient.fName = $scope.editingPatient.fName;
        		$scope.patient.middleInitial = $scope.editingPatient.middleInitial;
        		$scope.patient.lName = $scope.editingPatient.lName;
        		$scope.patient.phone = $scope.editingPatient.phone;
        		$scope.patient.address1 = $scope.editingPatient.address1;
        		$scope.patient.address2 = $scope.editingPatient.address2;
        		$scope.patient.city = $scope.editingPatient.city;
        		$scope.patient.state = $scope.editingPatient.state;
        		$scope.patient.gender = $scope.editingPatient.gender;
        		$scope.patient.password = $scope.editingPatient.passw1;
        		$scope.patient.dateAdded = $scope.editingPatient.dateAdded;
        		
        		if($scope.validateForm()) {
	        		$http(
	    		        {
	        		        method: "POST",
	        		        url: "/PatientFirst/services/patientservice/patient/save",
	        		        data: $scope.patient
			            }
	        		).success(
		                function(responseModel, status, headers, config) {
		                    if(responseModel.status == Utility.jsonResponse.SUCCESS) {
	                            Utility.showAlert("alertContainer", "success", true, 3, "<strong>Success!</strong> The record was successfully saved!");
		                    }
		                    else {
		                        Utility.showAlert("alertContainer", "danger", true, 3, "<strong>Error!</strong> " + responseModel.message);
		                    }
		                }
	                ).error(
	                    function(data, status, headers, config) {
	                        Utility.showAlert("alertContainer", "danger", true, 3, "<strong>Error!</strong> The attempt to Save has failed.");
	                    }
	                );
	        		
	        		$("#dlgEditPatient").modal('hide');
        		}
        	}
        	else {
        	    if($scope.validateForm()) {
            	    var newPatient = {
        	            id: -1,
            	        fName: $scope.editingPatient.fName,
            	        middleInitial: $scope.editingPatient.middleInitial,
            	        lName: $scope.editingPatient.lName,
            	        phone: $scope.editingPatient.phone,
            	        address1: $scope.editingPatient.address1,
            	        address2: $scope.editingPatient.address2,
            	        city: $scope.editingPatient.city,
            	        state: $scope.editingPatient.state,
            	        gender: $scope.editingPatient.gender,
            	        password: $scope.editingPatient.passw1,
            	        dateAdded: $scope.editingPatient.dateAdded
            	    }
            	    
            	    $http(
        	            {
        	                method: "PUT",
        	                url: "/PatientFirst/services/patientservice/patient/add",
        	                data: newPatient
        	            }
    	            ).success(
                        function(responseModel, status, headers, config) {
                            if(responseModel.status == Utility.jsonResponse.SUCCESS) {
                                Utility.showAlert("alertContainer", "success", true, 3, "<strong>Success!</strong> The new record was successfully added!");
                                $scope.patients.push(responseModel.data);
                                $scope.tableParameters.reload();
                            }
                            else {
                                Utility.showAlert("alertContainer", "danger", true, 3, "<strong>Error!</strong> " + responseModel.message);
                            }
                        }
            	    ).error(
        	            function(data, status, headers, config) {
        	                Utility.showAlert("alertContainer", "danger", true, 3, "<strong>Error!</strong> The attempt to create the new record has failed.");
        	            }
    	            );
            	    
            	    $("#dlgEditPatient").modal('hide');
        	    }
        	}
        }
        
        $scope.deletePatients = function() {
        	var selectedPatients = $scope.selectedPatients();
        	for(var patient in selectedPatients) {
        		$scope.deletePatient(selectedPatients[patient]);
        	}
        }
        
        $scope.deletePatient = function(patient) {
        	var patientDeleted = patient;
        	if(typeof(patientDeleted) === 'undefined' || patientDeleted == null) {
        		patientDeleted = $scope.patient;
        	}
        	
        	$http(
    	        {
    	            method: "DELETE",
    	            url: "/PatientFirst/services/patientservice/patient/delete/" + patientDeleted.id,
    	            patientName: patientDeleted.lName + ", " + patientDeleted.fName,
    	            patientId: patientDeleted.id
    	        }
	        ).success(
                function(responseModel, status, headers, config) {
                    if(responseModel.status == Utility.jsonResponse.SUCCESS) {
                        for(var i = 0; i < $scope.patients.length; i++) {
                            if($scope.patients[i].id == config.patientId) {
                                $scope.patients.splice(i, 1);
                                $scope.tableParameters.reload();
                                break;
                            }
                        }
                    
                        Utility.showAlert("alertContainer", "success", true, 3, "<strong>Success!</strong> [" + config.patientName + "] was successfully deleted.");
                    }
                    else {
                        Utility.showAlert("alertContainer", "danger", true, 3, "<strong>Error!</strong> [" + config.patientName + "] could not be deleted. Error Message: " + responseModel.message);
                    }
                }
            ).error(
                function(data, status, headers, config) {
                    Utility.showAlert("alertContainer", "danger", true, 3, "<strong>System Error!</strong> Deletion of [" + config.patientName + "] failed.");
                }
            );
        }
        
        $scope.validateForm = function() {
        	$scope.validatePassword();
    	    $scope.errorMessages = Utility.getAngularFormErrors($scope, "editPatientForm");
    	    return ($scope.errorMessages.length == 0);
    	}
        
        $scope.validatePassword = function() {
        	$scope.editPatientForm.txtPassword2.$setValidity("passwordMatch", true);
        	
    		if($scope.editingPatient.passw1 != $scope.editingPatient.passw2) {
    			$scope.editPatientForm.txtPassword2.$setValidity("passwordMatch", false);
    		}
        }
        
        $scope.openDatePicker = function($event) {
            $event.preventDefault();
            $event.stopPropagation();
            $scope.datePicker.opened = true;
        }
        
        $scope.init();
    }
    
]);